package edu.cs.usask.ca.silver.plugin.rcp.handlers.remove;

import org.apache.log4j.Logger;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.handlers.HandlerUtil;

import edu.cs.usask.ca.silver.businesslogic.ids.BaseId;
import edu.cs.usask.ca.silver.plugin.rcp.components.SilverTreeObject;
import edu.cs.usask.ca.silver.plugin.rcp.jobs.LoggerReportScheduler;
import edu.cs.usask.ca.silver.plugin.rcp.views.projectviewer.ProjectViewI;

/**
 * RemoveAction is an Action class that removes selected ID from Database. This
 * class identifies the ID type and call the corresponding method.
 * 
 * @author Yudi Xue
 * 
 */
public class RemoveTreeItemHandler extends AbstractHandler {
	private static Logger logger = Logger
			.getLogger(RemoveTreeItemHandler.class);

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		ProjectViewI view = (ProjectViewI) HandlerUtil
				.getActiveWorkbenchWindow(event).getActivePage()
				.findView(event.getParameter("projectviewid"));

		IStructuredSelection a = view.getTreeSelection();
		if (a.size() == 0)
			return null;

		Object[] selection = a.toArray();

		// temporary BaseId used for class casting
		BaseId temp;

		for (int i = 0; i < selection.length; i++) {
			// obtain BaseId from current entity in selection array
			temp = ((SilverTreeObject) selection[i]).getSilverObjectId();

			try {
				temp.deleteFromDatabase(view.getAssociatedStorage());

				/*
				 * there is a scenario where user select multiple elements and
				 * while selections are deleted in order, a parent (eg.mp) may
				 * be deleted before a child (eg.mv) is removed, this will
				 * result the child can not be found since it is already gone.
				 * Derby handles this well, however pgSQL needs to be checked.
				 */

				view.getTreeViewer().remove(selection[i]);

			} catch (Exception e) {
				LoggerReportScheduler.scheduleErrorLogging(logger,
						"error deleting from project view in remove tree item handler",
						e);
			}

		}

		return null;

	}

}
